package com.xgg.taiwuinfo.filter;

import android.content.Context;
import android.content.SharedPreferences;

import com.xgg.taiwuinfo.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;

public class FilterList {

    static private ArrayList<Filter> mList = new ArrayList<>();

    static public ArrayList<Filter> getList() { return mList;}

    static public void Init(Context ctx)
    {
        SharedPreferences sp = ctx.getSharedPreferences("TAIWU", Context.MODE_PRIVATE);
        String data = sp.getString("sp_filter", ctx.getString(R.string.defaultfilters));

        try
        {
            mList = new ArrayList<>();
            JSONArray arr = new JSONArray(data);
            for (int i = 0; i < arr.length(); i++)
            {
                Filter ft = Filter.Init((JSONObject)arr.get(i) , ctx);
                if (ft != null)
                {
                    mList.add(ft);
                }
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    static public void SaveToSP(Context ctx)
    {
        try{
            JSONArray arr = new JSONArray();
            for (int i = 0; i < mList.size(); i++)
            {
                arr.put(mList.get(i).getJsonObj());
            }
            SharedPreferences sp = ctx.getSharedPreferences("TAIWU", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("sp_filter" , arr.toString());
            editor.apply();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    static public void AddTail(String name , Context ctx)
    {
        if (mList == null)
        {
            mList = new ArrayList<>();
        }
        Filter ft = Filter.Init(name);
        mList.add(ft);
        SaveToSP(ctx);
    }

    //返回true代表可以添加或重命名
    static public boolean DupName(String name)
    {
        if (mList == null)
        {
            mList = new ArrayList<>();
            return true;
        }
        for (int i = 0 ; i < mList.size(); i++)
        {
            Filter ft = mList.get(i);
            if (ft.mName.equals(name))
            {
                return false;
            }
        }
        return true;
    }

    //删除指定过滤器
    static public boolean DeleteFilter(Filter filter)
    {
        if (mList.size() <= 1)
            return false;
        else {
            mList.remove(filter);
            return true;
        }
    }
}
